﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq.SqlClient;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;
using LitJson;


public class Menu
{
    public string type { get; set; }
    public string name { get; set; }
    public string key { get; set; }
    public string url { get; set; }
    public bool IsSub = false;
    public IList<Menu> sub_button = new List<Menu>();
}


public partial class manageWXCD : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ID"] == null)
        {
            Response.Write("<script>alert('非法登录！');location='../Default.aspx'</script>");
        }
        else
        {

            ShuaXinCaiDanXianShi();     
        }
    }

    protected void ShuaXinCaiDanXianShi()
    {
        for (int i = 1; i <= 3; i++)
        {
            for (int j = 0; j <= 5; j++)
            {
                Button bt1 = (Button)this.FindControl("ButtonCD" + i.ToString() + j.ToString());
                bt1.Text = "";
            }
        }

        ////删除菜单后清空输入框
        //TextBox1.Text = "";
        //RadioButtonList1.ClearSelection();
        //Label1.Text = "";
        //Label2.Text = "";
        //DropDownList1.DataSource = null;
        //DropDownList1.ClearSelection();
        //TextBox2.Text = "";

        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            //菜单10
            var r1 = (from q in ds.WeiXinCaiDan
                      where q.shunxuma == "10"
                      select q).FirstOrDefault();
            if (r1 != null)
            {
                Button bt1 = (Button)this.FindControl("ButtonCD10");
                bt1.Text = r1.name.ToString();

                //菜单10的子菜单
                var rd1 = from q in ds.WeiXinCaiDan
                          where SqlMethods.Like(q.shunxuma, "1%")
                          orderby q.shunxuma
                          select q;
                foreach (var r in rd1)
                {
                    Button bt2 = (Button)this.FindControl("ButtonCD" + r.shunxuma);
                    bt2.Text = r.name.ToString();
                }
            }

            //菜单20
            var r2 = (from q in ds.WeiXinCaiDan
                      where q.shunxuma == "20"
                      select q).FirstOrDefault();
            if (r2 != null)
            {
                Button bt3 = (Button)this.FindControl("ButtonCD20");
                bt3.Text = r2.name.ToString();

                //菜单20的子菜单
                var rd1 = from q in ds.WeiXinCaiDan
                          where SqlMethods.Like(q.shunxuma, "2%")
                          orderby q.shunxuma
                          select q;
                foreach (var r in rd1)
                {
                    Button bt4 = (Button)this.FindControl("ButtonCD" + r.shunxuma);
                    bt4.Text = r.name.ToString();
                }
            }


            //菜单30
            var r3 = (from q in ds.WeiXinCaiDan
                      where q.shunxuma == "30"
                      select q).FirstOrDefault();
            if (r3 != null)
            {
                Button bt5 = (Button)this.FindControl("ButtonCD30");
                bt5.Text = r3.name.ToString();

                //菜单10的子菜单
                var rd3 = from q in ds.WeiXinCaiDan
                          where SqlMethods.Like(q.shunxuma, "3%")
                          orderby q.shunxuma
                          select q;
                foreach (var r in rd3)
                {
                    Button bt6 = (Button)this.FindControl("ButtonCD" + r.shunxuma);
                    bt6.Text = r.name.ToString();
                }
            }
        }
    }

    //点击预览界面的菜单按钮时调出对应菜单项内容
    //输入参数 anniuid 是按钮ID， ID最后两位字符 =shunxuma(顺序码) 例如：anniuid=ButtonCD11   
    protected void DiaoChuCaiDanNeiRong(string anniuid)
    {
        string sxm = anniuid.Substring(anniuid.Length - 2, 2);//shunxuma
        HiddenFieldShunXuMa.Value = sxm;

        TextBox1.Text = "";
        RadioButtonList1.SelectedIndex = -1;
        TextBox2.Text = "";
        DropDownList1.ClearSelection();
        DropDownList1.Visible = false;
        Label1.Text = "";
        Label2.Text = "";

        //if (anniuid.Substring(anniuid.Length - 1, 1).ToString() == "0")
        //{
        //    ButtonAdd.Visible = true;
        //}
        //else
        //{
        //    ButtonAdd.Visible = false;
        //}


        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            var r1 = (from q in ds.WeiXinCaiDan
                      where q.shunxuma == sxm
                      select new
                      {
                          id = q.id,
                          shunxuma = q.shunxuma,
                          name = q.name == null ? "" : q.name,
                          type = q.type == null ? "" : q.type,
                          hf_gudingkey = q.hf_gudingkey == null ? "" : q.hf_gudingkey,
                          hf_yewuziliaoID = q.hf_yewuziliaoID == null ? -1 : q.hf_yewuziliaoID,
                          hf_waiwangdizhi = q.hf_waiwangdizhi == null ? "" : q.hf_waiwangdizhi
                      }).FirstOrDefault();
            if (r1 != null) //已有记录
            {
                HiddenFieldBianJi.Value = "edit"; //标记该菜单项是修改状态
                HiddenFieldJiLuID.Value = Convert.ToString(r1.id);

                TextBox1.Text = Convert.ToString(r1.name);

                if (r1.hf_gudingkey != "")
                {
                    RadioButtonList1.SelectedIndex = 0;
                    Label2.Visible = true;
                    DropDownList1.Visible = true;
                    Label2.Text = RadioButtonList1.Items[0].Text;

                    DropDownList1.DataSource = from q in ds.GuDingKey
                                               orderby q.id
                                               select q;
                    DropDownList1.DataValueField = "menu_key";
                    DropDownList1.DataTextField = "miaoshu";
                    DropDownList1.DataBind();
                    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(r1.hf_gudingkey));
                }
                else if (r1.hf_yewuziliaoID >= 0)
                {
                    RadioButtonList1.SelectedIndex = 1;
                    Label2.Visible = true;
                    DropDownList1.Visible = true;
                    Label2.Text = RadioButtonList1.Items[1].Text;

                    DropDownList1.DataSource = from q in ds.YeWuZiLiao
                                               where q.parentID >= 0
                                               orderby q.id
                                               select q;
                    DropDownList1.DataValueField = "id";
                    DropDownList1.DataTextField = "mingcheng";
                    DropDownList1.DataBind();
                    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(r1.hf_yewuziliaoID)));
                }
                else if (r1.hf_waiwangdizhi != "")
                {
                    RadioButtonList1.SelectedIndex = 2;
                    Label1.Text = RadioButtonList1.Items[2].Text;
                    TextBox2.Text = r1.hf_waiwangdizhi.ToString();
                    Label1.Visible = true;
                    TextBox2.Visible = true;
                }
            }
            else //新增
            {
                HiddenFieldBianJi.Value = "insert"; //标记该菜单项是修改状态
                HiddenFieldJiLuID.Value = "";
            }

        }

        Button bt = (Button)this.FindControl(anniuid);
        bt.Focus();
    }
    protected void ButtonCD11_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD11.ID);
    }
    protected void ButtonCD12_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD12.ID);
    }
    protected void ButtonCD13_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD13.ID);
    }
    protected void ButtonCD14_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD14.ID);
    }
    protected void ButtonCD15_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD15.ID);
    }
    protected void ButtonCD21_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD21.ID);
    }
    protected void ButtonCD22_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD22.ID);
    }
    protected void ButtonCD23_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD23.ID);
    }
    protected void ButtonCd24_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD24.ID);
    }
    protected void ButtonCD25_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD25.ID);
    }
    protected void ButtonCD31_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD31.ID);
    }
    protected void ButtonCD32_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD32.ID);
    }
    protected void ButtonCD33_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD33.ID);
    }
    protected void ButtonCD34_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD34.ID);
    }
    protected void ButtonCD35_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD35.ID);
    }
    protected void ButtonCD10_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD10.ID);
    }
    protected void ButtonCD20_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD20.ID);
    }
    protected void ButtonCD30_Click(object sender, EventArgs e)
    {
        DiaoChuCaiDanNeiRong(ButtonCD30.ID);
    }

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (DataClassesDataContext ds = new DataClassesDataContext())
        {

            switch (RadioButtonList1.SelectedIndex)
            {
                case 0://预设查询
                    Label2.Visible = true;
                    DropDownList1.Visible = true;
                    //ButtonAdd.Visible = true;
                    Label1.Visible = false;
                    TextBox2.Visible = false;
                    Label2.Text = RadioButtonList1.Items[0].Text;

                    DropDownList1.DataSource = from q in ds.GuDingKey
                                               orderby q.id
                                               select q;
                    DropDownList1.DataValueField = "menu_key";
                    DropDownList1.DataTextField = "miaoshu";
                    DropDownList1.DataBind();

                    if (HiddenFieldJiLuID.Value != "")
                    {
                        var r1 = (from q in ds.WeiXinCaiDan
                                  where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                                  where q.hf_gudingkey != ""
                                  select q).FirstOrDefault();
                        if (r1 != null)
                        {
                            DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(r1.hf_gudingkey));
                        }
                    }
                    break;
                case 1://返回业务资料
                    Label2.Visible = true;
                    DropDownList1.Visible = true;
                    //ButtonAdd.Visible = true;
                    Label1.Visible = false;
                    TextBox2.Visible = false;
                    Label2.Text = RadioButtonList1.Items[1].Text;

                    DropDownList1.DataSource = from q in ds.YeWuZiLiao
                                               where q.parentID >= 0
                                               orderby q.id
                                               select q;
                    DropDownList1.DataValueField = "id";
                    DropDownList1.DataTextField = "mingcheng";
                    DropDownList1.DataBind();

                    if (HiddenFieldJiLuID.Value != "")
                    {
                        var r1 = (from q in ds.WeiXinCaiDan
                                  where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                                  where q.hf_yewuziliaoID > 0
                                  select q).FirstOrDefault();
                        if (r1 != null)
                        {
                            DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(r1.hf_yewuziliaoID)));
                        }
                    }
                    break;
                case 2://链接到其他网站
                    Label2.Visible = false;
                    DropDownList1.Visible = false;
                    //ButtonAdd.Visible = false;
                    Label1.Visible = true;
                    TextBox2.Visible = true;
                    Label1.Text = RadioButtonList1.Items[2].Text;
                    break;
                default:
                    break;
            }
        }
    }

    protected void ShuaXinXianShiShuJu()
    {
        using (DataClassesDataContext ds = new DataClassesDataContext())
        {

        }
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {

    }


    //保存菜单信息
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text.Trim() != "")
        {
            using (DataClassesDataContext ds = new DataClassesDataContext())
            {
                if ((HiddenFieldShunXuMa.Value.ToString().Substring(1, 1) == "0") && (!HaveSub(HiddenFieldShunXuMa.Value.ToString())))//没有子菜单的一级菜单
                {
                    if (HiddenFieldBianJi.Value == "edit")
                    {
                        var r0 = (from q in ds.WeiXinCaiDan
                                  where q.shunxuma == Convert.ToString(HiddenFieldShunXuMa.Value)
                                  select q).FirstOrDefault();
                        r0.name = TextBox1.Text.Trim();
                        ds.SubmitChanges();
                    }
                    else//insert
                    {
                        WeiXinCaiDan p = new WeiXinCaiDan();
                        p.name = TextBox1.Text.Trim();
                        p.shunxuma = HiddenFieldShunXuMa.Value.ToString();
                        ds.WeiXinCaiDan.InsertOnSubmit(p);
                        ds.SubmitChanges();
                    }

                }
                else
                {
                    if (HiddenFieldShunXuMa.Value.ToString().Substring(1, 1) == "0")//一级菜单，只改名字
                    {
                        var r01 = (from q in ds.WeiXinCaiDan
                                   where q.shunxuma == Convert.ToString(HiddenFieldShunXuMa.Value)
                                   select q).FirstOrDefault();
                        r01.name = TextBox1.Text.Trim();
                        ds.SubmitChanges();
                    }
                    else
                    {
                        switch (RadioButtonList1.SelectedIndex)//子菜单
                        {
                            case 0://预设查询
                                if (DropDownList1.SelectedIndex >= 0)
                                {
                                    if (HiddenFieldBianJi.Value == "insert")
                                    {
                                        WeiXinCaiDan p = new WeiXinCaiDan();
                                        p.shunxuma = Convert.ToString(HiddenFieldShunXuMa.Value);
                                        p.name = TextBox1.Text.Trim();
                                        p.type = "click";
                                        p.hf_gudingkey = DropDownList1.SelectedValue.ToString();
                                        p.hf_waiwangdizhi = "";
                                        p.hf_yewuziliaoID = -1;
                                        ds.WeiXinCaiDan.InsertOnSubmit(p);
                                        ds.SubmitChanges();
                                    }
                                    else if (HiddenFieldBianJi.Value == "edit")
                                    {
                                        var r1 = (from q in ds.WeiXinCaiDan
                                                  where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                                                  select q).FirstOrDefault();
                                        r1.name = TextBox1.Text.Trim();
                                        r1.type = "click";
                                        r1.hf_gudingkey = DropDownList1.SelectedValue.ToString();
                                        r1.hf_waiwangdizhi = "";
                                        r1.hf_yewuziliaoID = -1;
                                        ds.SubmitChanges();
                                    }
                                }
                                break;
                            case 1://返回业务资料
                                if (DropDownList1.SelectedIndex >= 0)
                                {
                                    if (HiddenFieldBianJi.Value == "insert")
                                    {
                                        WeiXinCaiDan p = new WeiXinCaiDan();
                                        p.shunxuma = Convert.ToString(HiddenFieldShunXuMa.Value);
                                        p.name = TextBox1.Text.Trim();
                                        p.type = "click";
                                        p.hf_gudingkey = "";
                                        p.hf_waiwangdizhi = "";
                                        p.hf_yewuziliaoID = Convert.ToInt32(DropDownList1.SelectedValue);
                                        ds.WeiXinCaiDan.InsertOnSubmit(p);
                                        ds.SubmitChanges();
                                    }
                                    else if (HiddenFieldBianJi.Value == "edit")
                                    {
                                        var r1 = (from q in ds.WeiXinCaiDan
                                                  where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                                                  select q).FirstOrDefault();
                                        r1.name = TextBox1.Text.Trim();
                                        r1.type = "click";
                                        r1.hf_gudingkey = "";
                                        r1.hf_waiwangdizhi = "";
                                        r1.hf_yewuziliaoID = Convert.ToInt32(DropDownList1.SelectedValue);
                                        ds.SubmitChanges();
                                    }
                                }
                                break;
                            case 2://链接到其他网站
                                if (TextBox2.Text.Trim() != "")
                                {
                                    if (HiddenFieldBianJi.Value == "insert")
                                    {
                                        WeiXinCaiDan p = new WeiXinCaiDan();
                                        p.shunxuma = Convert.ToString(HiddenFieldShunXuMa.Value);
                                        p.name = TextBox1.Text.Trim();
                                        p.type = "view";
                                        p.hf_gudingkey = "";
                                        p.hf_waiwangdizhi = TextBox2.Text.Trim();
                                        p.hf_yewuziliaoID = -1;
                                        ds.WeiXinCaiDan.InsertOnSubmit(p);
                                        ds.SubmitChanges();
                                    }
                                    else if (HiddenFieldBianJi.Value == "edit")
                                    {
                                        var r1 = (from q in ds.WeiXinCaiDan
                                                  where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                                                  select q).FirstOrDefault();
                                        r1.name = TextBox1.Text.Trim();
                                        r1.type = "view";
                                        r1.hf_gudingkey = "";
                                        r1.hf_waiwangdizhi = TextBox2.Text.Trim();
                                        r1.hf_yewuziliaoID = -1;
                                        ds.SubmitChanges();
                                    }
                                }
                                break;
                        }
                    }
                }
            }

            ShuaXinCaiDanXianShi();
        }
        else
        {


        }
    }
    protected void ButtonDel_Click(object sender, EventArgs e)
    {
        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            if ((HiddenFieldJiLuID.Value != null) && (HiddenFieldBianJi.Value == "edit"))
            {
                if (HiddenFieldShunXuMa.Value.ToString().Substring(1, 1) != "0")//是一级菜单，要判断是否有二级菜单，如果有则要先去删除二级菜单先
                {
                    var r1 = (from q in ds.WeiXinCaiDan
                              where q.id == Convert.ToInt32(HiddenFieldJiLuID.Value)
                              select q).FirstOrDefault();
                    ds.WeiXinCaiDan.DeleteOnSubmit(r1);
                    ds.SubmitChanges();

                    ShuaXinCaiDanXianShi();
                }
                else
                {
                    Response.Write("<script>alert('该一级菜单已有对应的二级子菜单，不能删除！')</script>");
                }

            }
        }
    }


    ///
    /// 根据Menu列表生成符合微信规范的创建菜单JSon
    ///一级菜单不超过3个，二级菜单不超过5个
    ///
    ///微信唯一标示
    ///菜单列表，type为click时url留空，view时key留空
    public string CreateMenuJson(IList<Menu> munuList)
    {
        JsonData jd = new JsonData();
        jd["button"] = new JsonData();
        foreach (Menu menu in munuList)
        {
            if (menu.IsSub)
            {
                JsonData json = new JsonData();
                json["name"] = menu.name;
                json["sub_button"] = new JsonData();
                foreach (Menu item in menu.sub_button)
                {
                    JsonData tmpJson = new JsonData();
                    tmpJson["type"] = item.type;
                    tmpJson["name"] = item.name;
                    if (item.key != null)
                    {
                        tmpJson["key"] = item.key;
                    }
                    else
                    {
                        tmpJson["url"] = item.url;
                    }
                    json["sub_button"].Add(tmpJson);
                }
                jd["button"].Add(json);
            }
            else
            {
                JsonData tmpJson = new JsonData();
                tmpJson["type"] = menu.type;
                tmpJson["name"] = menu.name;
                if (menu.key != null)
                {
                    tmpJson["key"] = menu.key;
                }
                else
                {
                    tmpJson["url"] = menu.url;
                }
                jd["button"].Add(tmpJson);
            }
        }
        return jd.ToJson();
    }


    private string PostWebRequest(string postUrl, string menuInfo)
    {
        string returnValue = string.Empty;
        try
        {
            byte[] byteData = Encoding.UTF8.GetBytes(menuInfo);
            Uri uri = new Uri(postUrl);
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteData.Length;
            //定义Stream信息
            Stream stream = webReq.GetRequestStream();
            stream.Write(byteData, 0, byteData.Length);
            stream.Close();
            //获取返回信息
            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            returnValue = streamReader.ReadToEnd();
            //关闭信息
            streamReader.Close();
            response.Close();
            stream.Close();
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.ToString();
        }
        return returnValue;
    }

    private string getMenuInfo()
    {

        return "{\"button\":[{\"name\":\"菜单一\",\"sub_button\":[{\"type\":\"click\",\"name\":\"子菜单一一\",\"key\":\"V1001_HELLO_WORLD\"},{\"type\":\"click\",\"name\":\"子菜单一二\",\"key\":\"V1001_GOOD\"}]},{\"name\":\"菜单二\",\"sub_button\":[{\"type\":\"click\",\"name\":\"子菜单二一\",\"key\":\"V1002_HELLO_WORLD\"},{\"type\":\"click\",\"name\":\"子菜单二二\",\"key\":\"V1002_GOOD\"}]},{\"name\":\"菜单三\",\"sub_button\":[{\"type\":\"click\",\"name\":\"子菜单三一\",\"key\":\"V1003_GOOD\"}]}]}";
    }

    protected void btnDeleteMenu_Click(object sender, EventArgs e)
    {
        string postUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={0}";
        postUrl = string.Format(postUrl, GetAccessToken());
        string menuInfo = getMenuInfo();
        lblResult.Text = "结果：" + PostWebRequest(postUrl, menuInfo);
    }

    protected string GetAccessToken()
    {
        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            //在ButtonQiYongCaiDan_Click里已经判断这两个值是否存在，这里不用再判断
            var rd1 = (from q in ds.XiTongXinXiJiLu
                       where q.biaoti == "appid"
                       where q.neirong != null
                       where q.neirong != ""
                       select q).FirstOrDefault();
            string appid = rd1.neirong.ToString();

            var rd2 = (from q in ds.XiTongXinXiJiLu
                       where q.biaoti == "appsecret"
                       where q.neirong != null
                       where q.neirong != ""
                       select q).FirstOrDefault();
            string appsecret = rd2.neirong.ToString();


            string accessToken = string.Empty;
            string getUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
            //getUrl = string.Format(getUrl, "你申请的appid", "你申请的secret");
            getUrl = string.Format(getUrl, appid, appsecret);
            Uri uri = new Uri(getUrl);
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
            webReq.Method = "POST";

            //获取返回信息
            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string returnJason = streamReader.ReadToEnd();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(returnJason);
            object value;
            if (json.TryGetValue("access_token", out value))
            {
                accessToken = value.ToString();
            }
            return accessToken;
        }
    }


    //向微信公众平台申请启用菜单
    protected void ButtonQiYongCaiDan_Click(object sender, EventArgs e)
    {

        IList<Menu> list = new List<Menu>();

        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            var bd1 = (from q in ds.XiTongXinXiJiLu
                       where q.biaoti == "appid"
                       where q.neirong != null
                       where q.neirong != ""
                       select q).Any();

            var bd2 = (from q in ds.XiTongXinXiJiLu
                       where q.biaoti == "appsecret"
                       where q.neirong != null
                       where q.neirong != ""
                       select q).Any();
            if (bd1 && bd2)//已经有了在公众平台申请自定义菜单使用的AppId和AppSecret才能启用发布菜单
            {

                //菜单一及对应子菜单
                var rd1 = from q in ds.WeiXinCaiDan
                          where q.shunxuma.Substring(0, 1) == "1"
                          orderby q.shunxuma.Substring(1, 1)
                          select q;
                Menu m10 = new Menu();
                foreach (var r in rd1)
                {
                    if (r.shunxuma.Substring(1, 1) == "0")//是一级菜单
                    {
                        if (HaveSub(r.shunxuma))
                        {
                            m10.name = r.name;
                            m10.IsSub = true;

                        }
                        else
                        {
                            m10.type = r.type;
                            m10.name = r.name;

                            if (r.hf_gudingkey != "")
                            {
                                m10.key = r.hf_gudingkey;
                            }
                            else if (r.hf_yewuziliaoID >= 0)
                            {
                                m10.key = Convert.ToString(r.hf_yewuziliaoID);
                            }
                            else if (r.hf_waiwangdizhi != "")
                            {
                                m10.url = r.hf_waiwangdizhi;
                            }
                        }
                    }
                    else//二级子菜单
                    {
                        //m1.IsSub = true;

                        Menu m2 = new Menu();
                        m2.name = r.name;
                        m2.type = r.type;
                        if (r.hf_gudingkey != "")
                        {
                            m2.key = r.hf_gudingkey;
                        }
                        else if (r.hf_yewuziliaoID >= 0)
                        {
                            m2.key = Convert.ToString(r.hf_yewuziliaoID);
                        }
                        else if (r.hf_waiwangdizhi != "")
                        {
                            m2.url = r.hf_waiwangdizhi;
                        }
                        m10.sub_button.Add(m2);


                    }
                }
                if (rd1 != null && rd1.Count() > 0)
                {
                    list.Add(m10);
                }


                //菜单二及对应子菜单
                var rd2 = from q in ds.WeiXinCaiDan
                          where q.shunxuma.Substring(0, 1) == "2"
                          orderby q.shunxuma.Substring(1, 1)
                          select q;
                Menu m20 = new Menu();
                foreach (var r in rd2)
                {
                    if (r.shunxuma.Substring(1, 1) == "0")//是一级菜单
                    {
                        if (HaveSub(r.shunxuma))
                        {
                            m20.name = r.name;
                            m20.IsSub = true;

                        }
                        else
                        {
                            m20.type = r.type;
                            m20.name = r.name;
                            if (r.hf_gudingkey != "")
                            {
                                m20.key = r.hf_gudingkey;
                            }
                            else if (r.hf_yewuziliaoID >= 0)
                            {
                                m20.key = Convert.ToString(r.hf_yewuziliaoID);
                            }
                            else if (r.hf_waiwangdizhi != "")
                            {
                                m20.url = r.hf_waiwangdizhi;
                            }
                        }

                    }
                    else//二级子菜单
                    {
                        //m20.IsSub = true;

                        Menu m2 = new Menu();
                        m2.name = r.name;
                        m2.type = r.type;
                        if (r.hf_gudingkey != "")
                        {
                            m2.key = r.hf_gudingkey;
                        }
                        else if (r.hf_yewuziliaoID >= 0)
                        {
                            m2.key = Convert.ToString(r.hf_yewuziliaoID);
                        }
                        else if (r.hf_waiwangdizhi != "")
                        {
                            m2.url = r.hf_waiwangdizhi;
                        }
                        m20.sub_button.Add(m2);

                    }
                }
                if (rd2 != null && rd2.Count() > 0)
                {
                    list.Add(m20);
                }



                //菜单三及对应子菜单
                var rd3 = from q in ds.WeiXinCaiDan
                          where q.shunxuma.Substring(0, 1) == "3"
                          orderby q.shunxuma.Substring(1, 1)
                          select q;
                Menu m30 = new Menu();
                foreach (var r in rd3)
                {

                    if (r.shunxuma.Substring(1, 1) == "0")//是一级菜单
                    {
                        if (HaveSub(r.shunxuma))
                        {
                            m30.name = r.name;
                            m30.IsSub = true;

                        }
                        else
                        {
                            m30.type = r.type;
                            m30.name = r.name;
                            if (r.hf_gudingkey != "")
                            {
                                m30.key = r.hf_gudingkey;
                            }
                            else if (r.hf_yewuziliaoID >= 0)
                            {
                                m30.key = Convert.ToString(r.hf_yewuziliaoID);
                            }
                            else if (r.hf_waiwangdizhi != "")
                            {
                                m30.url = r.hf_waiwangdizhi;
                            }
                        }

                    }
                    else//二级子菜单
                    {
                        //m1.IsSub = true;

                        Menu m2 = new Menu();
                        m2.name = r.name;
                        m2.type = r.type;
                        if (r.hf_gudingkey != "")
                        {
                            m2.key = r.hf_gudingkey;
                        }
                        else if (r.hf_yewuziliaoID >= 0)
                        {
                            m2.key = Convert.ToString(r.hf_yewuziliaoID);
                        }
                        else if (r.hf_waiwangdizhi != "")
                        {
                            m2.url = r.hf_waiwangdizhi;
                        }
                        m30.sub_button.Add(m2);

                    }
                }
                if (rd3 != null && rd3.Count() > 0)
                {
                    list.Add(m30);
                }

                string json = CreateMenuJson(list);

                string postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}";
                postUrl = string.Format(postUrl, GetAccessToken());
                string menuInfo = json;
                lblResult.Text = "结果：" + PostWebRequest(postUrl, menuInfo);

            }
            else
            {
                Response.Write("<script>alert('AppId和AppSecret还没有设置或者信息不完整，不能启用菜单！')</script>");
            }
        }
    }


    //某个一级菜单有子菜单则返回true ，没有则返回false ,sxm是顺序码 
    protected bool HaveSub(string sxm)
    {

        using (DataClassesDataContext ds = new DataClassesDataContext())
        {
            var count = (from q in ds.WeiXinCaiDan
                         where q.shunxuma.Substring(0, 1) == sxm.Substring(0, 1)
                         select q).Count();
            if (count < 2)//没有子菜单
            {
                return false;
            }
            else//有子菜单
            {
                return true;
            }
        }
    }
}